/**
 * Copyright  2025, Hai Yue Xing He Technology Co., Ltd
 * 
 * @author        ZHAO LIMIN
 * @version       1.0.1
 * @since         2025-04
 * BelialHunter.ts   猎人，用于追踪精灵，并根据最近的路径，进行处理
 */
import { _decorator, Component, ImageAsset, Node, resources, Sprite, SpriteFrame, Texture2D } from 'cc';
import { SpritePlayer } from './SpritePlayer';
import { HNetsPolyline } from '../hyxh/core/HYXHNetsPolyline';
import { IParametersOptions } from '../hyxh/core/HBase';
import { ICartesian } from '../hyxh/core/Cartesian';
import { Check } from '../hyxh/core/Check';
import { defined } from '../hyxh/core/Defined';
import { SecenseTools } from './SecenseTools';
import { Cartesian3 } from '../hyxh/core/Cartesian3';
import { Cion } from './cion';
import { SecenesManager } from './SecenesManager';
import { HImageResource } from './HResource';
const { ccclass, property } = _decorator;

@ccclass('BelialHunter')
export class BelialHunter extends Component {  

    @property('network')
    private _network: HNetsPolyline = null!;
    @property('seceneController')
    private _seceneController: SecenseTools = null!;
    @property('thisnode')
    private thisNode: Node = null;

    private _image_url = 0; 

    /* 自动移动的周期 */
    private speedDeltaTime: number = 0;
    /* 刷新周期，用于根据精灵的位置，进行导航 */
    private fleshDeltaTime: number = 0;
    /* 出队 */
    private path: Array<ICartesian> = [];

    private stimes: number = 0;
    private ftimes: number = 0;

    private _node_pos: Cion = null!;

    private _model: number = 0;

    private targets: number[] = [];
    private tarcursor = 0;

    isActive = false;
   
    /**
     * {
     *           "name":"belial001",
     *           "image":"chaser/chaser5",
     *           "startPosition":[-32,367.0, 0.0],
     *           "width": 32,
     *           "height": 32,
     *           "mainhunter": true,
     *           "speedCycle": 2,
     *           "fleshCycle": 10,
     * }
     * @param option 
     */
    public initialize(option: IParametersOptions) {
        this.name = option.name;
        this.speedDeltaTime = option.speed;
        this.fleshDeltaTime = option.flesh;
        this._network = option.network; 
        this._image_url = option.image?? 9001006;
        const _x = option.startPosition[0]?? 0.0;
        const _y = option.startPosition[1]?? 0.0;
        const _z = option.startPosition[2]?? 0.0;
        
        this.thisNode = new Node(this.name);
        this.thisNode.parent = this.node;
        this._model = option.model??1;
        this.targets = option.path??[30, 13, 36, 10, 0, 1, 2, 5];
        this.tarcursor = 0;

        ////this.tagertSpritePlayer = option.TSPlayer;
        this.thisNode.setParent(this.node); // 将节点添加到场景中 
        this.thisNode.setPosition(_x, _y, _z); // 设置节点的位置为 (0, 0, 0)

        this.isActive = true;
    }

    public movetoFirstPosition() {
        if ( !defined(this._node_pos) && defined(this._seceneController) ) {
            /* 在开始位置 */
            this._node_pos = this._seceneController.findNearestPoint(new Cartesian3(
                this.thisNode.position.x, 
                this.thisNode.position.y, 
                this.thisNode.position.z));
            if(!defined(this._node_pos)) {
                return; 
            }
            this.moveForNodePos(this._node_pos);
        }
    }

    public getSpriteAndHunterPos(): Cion[] | undefined {
        if (!defined(this._node_pos) || !defined(this._seceneController) ) {
            return undefined;
        }
        if (!defined(this._seceneController.spritePlayer)){
            return undefined;
        }

        const _sprite_node_pos = this._seceneController.spritePlayer.getNodePosition();
        if (!defined(_sprite_node_pos)){
            return undefined;    
        } 
        return [this._node_pos, _sprite_node_pos];
    }

    public loadResources() {
        if (!defined(this._image_url)){
            return ;
        }        
        const frameResource = SecenesManager.getInstance().getResource(this._image_url) as HImageResource;
        if (!defined(frameResource)) {
            return;
        }
        SecenesManager.showImage(this.thisNode, frameResource);
    }

    update(deltaTime: number) {
        /* 判断是否步骤  */
        if(!this.isActive) {
            return;
        }
        this.stimes += deltaTime;
        if ( this.stimes >= this.speedDeltaTime ){
            /* */
            this.movetoFirstPosition();
            // if (this._seceneController.hasSpritePlayer()){
            //     this._seceneController.onEventForSpriteMovePos(this);
            // }
            this.movenext();
            this.stimes = 0;
        }
        this.ftimes += deltaTime;
        if ( this.ftimes >= this.fleshDeltaTime ){
            this.flushPath();
            this.ftimes = 0;
        }
    }
    movenext() {
        Check.defined("this.path", this.path);
        
        if (this.path.length == 0) {
            return;
        } 
        let next = this.path.shift();
        if (!defined(next)) {
            return ;
        }

        /* 判断当前位置，是否和精灵 */
        const new_pos = this._seceneController.findNearestPoint(next);
        if(!defined(new_pos)) {
            return; 
        }
        this.moveForNodePos(new_pos);
    }
    public setSeceneController(secenController: SecenseTools) {
        this._seceneController = secenController; 
    }

    public getSeceneController() : SecenseTools {
        return this._seceneController; 
    }

    public moveForNodePos( new_node_pos: Cion) {
        if(!SecenseTools.LOCL_SIGN) {
            SecenseTools.LOCL_SIGN = true;
            try {  
                if (!defined(new_node_pos)) {
                    return;
                }
                this._node_pos = new_node_pos;
                this.thisNode.setPosition(this._node_pos.position.x, this._node_pos.position.y, this._node_pos.position.z);
            }catch(error){
                console.error(error);
            }finally{
                SecenseTools.LOCL_SIGN = false;
            }
        }
    }

    flushPath() {
        Check.defined("this._network", this._network);
        Check.typeOf.object("this._network", this._network);       

        /* 获得当前Sprite 的位置 */        
        let pos = this.thisNode.getPosition();
        if (!defined(pos)) {
            return;
        }
        let cur_sprite_pos = this._network.indexPointIndicate( new Cartesian3( pos.x, pos.y, pos.z ));
        if (!defined(cur_sprite_pos)){
            return;
        }
        if (cur_sprite_pos.length < 2){
            if (!defined(this._node_pos)) {
                return;
            }
            cur_sprite_pos = [this._node_pos.points[0], this._node_pos.points[1]];
        }

        if(!defined(this._seceneController.spritePlayer)){
            return ;
        }
        let sprite_pos = this._seceneController.spritePlayer.getPositionIndices();
        if ( !defined(sprite_pos)){
           if (defined(this.targets)) {
                sprite_pos = [this.targets[0], this.targets[1]] as number[];
           }
        }

        if ( sprite_pos.length < 2 ){
            if (defined(this.targets)) {
                sprite_pos = [this.targets[0], this.targets[1]] as number[];
            }
        }
        let _new_path: ICartesian[] = [];
        if (this._model == 1) {
            const _t_new_path = this._network.navigationMinDist(
                cur_sprite_pos[0],
                cur_sprite_pos[1],
                sprite_pos[0],
                sprite_pos[1]);
            if (defined(_t_new_path) && (_t_new_path.length > 0)){
                /* 最短路径 */
                _new_path.push(..._t_new_path);
                _t_new_path.splice(0, _t_new_path.length);  
                _t_new_path.length = 0;
            }
        } else if ( this._model == 2 ) {
            const _t_new_path = this._network.navigationMaxDist(
                cur_sprite_pos[0],
                cur_sprite_pos[1],
                sprite_pos[0],
                sprite_pos[1]);
            if (defined(_t_new_path) && (_t_new_path.length > 0)){
                /* 最短路径 */
                _new_path.push(..._t_new_path);
                _t_new_path.splice(0, _t_new_path.length);  
                _t_new_path.length = 0;
            }

        } else if ( this._model == 3 ) {
            const _t_new_path = this._network.navigationRandomDist(
                cur_sprite_pos[0],
                cur_sprite_pos[1],
                sprite_pos[0],
                sprite_pos[1]);
            if (defined(_t_new_path) && (_t_new_path.length > 0)){
                /* 最短路径 */
                _new_path.push(..._t_new_path);
                _t_new_path.splice(0, _t_new_path.length);  
                _t_new_path.length = 0;
            } 
        } else if ( this._model == 4 ) {
            if ( this.tarcursor > this.targets.length - 2 ) {
                this.tarcursor = 0;
            }
            const _t_new_path = this._network.navigationWithPathDist( 
                cur_sprite_pos[0],
                cur_sprite_pos[1],
                this.targets,
                this.tarcursor,
            );
            if (defined(_t_new_path) && (_t_new_path.length > 0)){
                /* 最短路径 */
                _new_path.push(..._t_new_path);
                _t_new_path.splice(0, _t_new_path.length);  
                _t_new_path.length = 0;
            } 
            this.tarcursor+= 2;
        }        
        if (!defined(_new_path)) {
            return;
        }
        if (_new_path.length <= 0 ){
            return;
        }
        if (defined(this.path) && (this.path.length >0 )){
            this.path.splice(0, this.path.length);
            this.path.length = 0;
        }
        if (!defined(this.path)){
            this.path = [];
        }
        this.path.push(..._new_path);
    }

    getNodePosition(): Cion {
        return this._node_pos;
    }
}


